import { IKvManager } from './IKvManager';
import data_preferences from '@ohos.data.preferences';
import { ValueType } from '@kit.ArkData';

const TAG: string = '[PreferencesKvManager]'

export class PreferencesKvManager implements IKvManager {

  private preferences: data_preferences.Preferences = null;

  get(key: string, defValue: ValueType): Promise<ValueType> {
    return new Promise((resolve, reject) => {
      if (this.preferences == null) {
        reject("preferences is null");
      } else {
        this.preferences.has(key).then((result) => {
          this.preferences.get(key, defValue).then((value: ValueType) => {
            resolve(value);
          }).catch((error) => {
            reject(error);
          });
        }).catch((error) => {
          reject(error);
        });
      }
    });
  }

  getSync(key: string, defValue: ValueType): ValueType {
    if (this.preferences && this.preferences.hasSync(key)){
      let value = this.preferences.getSync(key, defValue) as ValueType;
      return value;
    }
    return defValue;
  }

  put(key: string, value: ValueType): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.preferences == null) {
        reject("preferences is null");
      } else {
        this.preferences.put(key, value).then(() => {
          this.commit().then((result) => {
            resolve();
          }).catch((error) => {
            reject(error);
          });
        }).catch((error) => {
          reject(error);
        });
      }
    });
  }

  putSync(key: string, value: ValueType): void {
    if (this.preferences != null) {
      this.preferences.putSync(key, value)
    }
  }

  commit(): Promise<void> {
    return this.preferences.flush();
  }

  has(key: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (this.preferences == null) {
        reject("preferences is null");
      } else {
        this.preferences.has(key).then((result) => {
          resolve(result);
        }).catch((error) => {
          reject(error);
        });
      }
    });
  }

  init(context): Promise<void> {
    return new Promise((resolve, reject) => {
      try {
        data_preferences.getPreferences(context, 'jncj').then((object) => {
          this.preferences = object;
          resolve();
        }).catch((err) => {
          reject();
        });
      } catch (err) {
        reject();
      }
    });
  }
}